<?php

namespace Biz\Services\Site;

use Lumen\Logger\Logger;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Biz\Constants\Site\SiteOrderConstants;
use Biz\Criteria\Site\SiteFilterCriterion;
use Biz\Criteria\Site\LocaleFilterCriterion;
use Lumen\Core\Exceptions\BusinessException;
use Biz\Models\Site\SiteOrderRegistrationFee;
use Illuminate\Contracts\Pagination\Paginator;
use Biz\Repositories\Site\SiteOrderRegistrationFeeRepository;

/**
 * SiteOrderRegistrationFeeService.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class SiteOrderRegistrationFeeService
{
    /**
     * @var \Lumen\Repository\Contracts\RepositoryContract
     */
    protected $repository;

    /**
     * @var SiteOrderService
     */
    protected $orderService;

    /**
     * RepositoryController constructor.
     *
     * @param SiteOrderRegistrationFeeRepository $repository
     * @param SiteOrderService                   $orderService
     */
    public function __construct(SiteOrderRegistrationFeeRepository $repository, SiteOrderService $orderService)
    {
        $this->repository                = $repository;
        $this->orderService              = $orderService;
    }

    /**
     * 列表页.
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|mixed
     */
    public function index(Request $request): Paginator
    {
        $site_id  = $request->get('site_id');
        $pageSize = $request->get('page_size', 10);

        $results = $this->repository
            ->setCacheLifetime(0)
            ->with(['order'])
            //->pushCriterion(new SiteFilterCriterion($site_id))
            //->pushCriterion(new LocaleFilterCriterion())
            ->paginate($pageSize);

        return $results;
    }

    /**
     * Find.
     *
     * @param int $id
     *
     * @throws BusinessException
     *
     * @return SiteOrderRegistrationFee
     */
    public function find(int $id): SiteOrderRegistrationFee
    {
        $orderRegistrationFee = $this->repository->find($id);
        if (is_null($orderRegistrationFee)) {
            throw new BusinessException(trans('site/order/registration-fee.not_found'));
        }

        return $orderRegistrationFee;
    }

    /**
     * Find By uid.
     *
     * @param string $uid
     *
     * @throws BusinessException
     *
     * @return SiteOrderRegistrationFee
     */
    public function findByUid(string $uid): SiteOrderRegistrationFee
    {
        $id   = SiteOrderRegistrationFee::decodeUid($uid);

        return $this->find($id);
    }

    /**
     * With find.
     *
     * @param int   $id
     * @param array $with
     *
     * @throws BusinessException
     *
     * @return SiteOrderRegistrationFee
     */
    public function findWith(int $id, $with = []): SiteOrderRegistrationFee
    {
        $site = $this->repository->with($with)->find($id);
        if (is_null($site)) {
            throw new BusinessException(trans('site/order/registration-fee.not_found'));
        }

        return $site;
    }

    /**
     * Find By Site Id.
     *
     * @param int $site_id
     *
     * @throws BusinessException
     *
     * @return bool
     */
    public function findBySiteId(int $site_id)
    {
        $orderRegistrationFee = $this->repository
            ->pushCriterion(new SiteFilterCriterion($site_id))
            ->findFirst();

        return $orderRegistrationFee;
    }

    /**
     * Find.
     *
     * @param string $registration_no
     *
     * @throws BusinessException
     *
     * @return bool
     */
    public function findByRepeatRegistrationNo(string $registration_no)
    {
        $registration = $this->repository
            ->where('registration_no', $registration_no)
            ->findFirst();

        return $registration;
    }

    /**
     * Handle Url.
     *
     * @param array $data
     *
     * @throws BusinessException
     *
     * @return void
     */
    public function checkRegistrationNo(array $data): void
    {
        $registration_no     = $data['registration_fee']['registration_no'];
        $menu                = $this->findByRepeatRegistrationNo($registration_no);
        if ($menu) {
            throw new BusinessException(trans('site/order/registration-fee.registration_no_repeat'));
        }
    }

    /**
     * Store.
     *
     * @param Request $request
     *
     * @throws \Exception
     *
     * @return SiteOrderRegistrationFee
     */
    public function store(Request $request): SiteOrderRegistrationFee
    {
        // Get Current User
        /** @var User $user */
        $user = $request->user();

        $data            = $request->all();
        $data['user_id'] = $user->id;

        return $this->create($data);
    }

    /**
     * Create.
     *
     * @param array $data
     *
     * @throws \Exception
     *
     * @return SiteOrderRegistrationFee
     */
    public function create(array $data): SiteOrderRegistrationFee
    {
        // Check
        $this->checkRegistrationNo($data);

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            // 创建订单
            $data['type']    = SiteOrderConstants::TYPE_REGISTRATION_FEE;
            $order           = $this->orderService->create($data);

            $data['registration_fee']['order_id'] = $order->id;
            $orderRegistrationFee                 = $this->repository->create($data['registration_fee']);
            if (! $orderRegistrationFee) {
                throw new BusinessException(trans('site/order/registration-fee.create_fail'));
            }
            $orderRegistrationFee->load('order');

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return $orderRegistrationFee;
    }

    /**
     * Detail.
     *
     * @param string $id
     *
     * @throws BusinessException
     *
     * @return SiteOrderRegistrationFee
     */
    public function show(string $id): SiteOrderRegistrationFee
    {
        $id   = SiteOrderRegistrationFee::decodeUid($id);
        $site = $this->findWith($id, ['order']);

        return $site;
    }

    /**
     * Edit.
     *
     * @param string $id
     * @param array  $data
     *
     * @throws \Exception
     *
     * @return SiteOrderRegistrationFee
     */
    public function edit(string $id, array $data): SiteOrderRegistrationFee
    {
        $id   = SiteOrderRegistrationFee::decodeUid($id);

        return $this->update($id, $data);
    }

    /**
     * Update.
     *
     * @param int   $id
     * @param array $data
     *
     * @throws \Exception
     *
     * @return SiteOrderRegistrationFee
     */
    public function update(int $id, array $data): SiteOrderRegistrationFee
    {
        $orderRegistrationFee = $this->find($id);

        // Check
        if ($orderRegistrationFee->registration_no != $data['registration_no']) {
            $this->checkRegistrationNo($data);
        }

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            $this->orderService->update($orderRegistrationFee->order_id, $data);

            $orderRegistrationFee   = $this->repository->update($orderRegistrationFee, $data['registration_fee']);
            if (! $orderRegistrationFee) {
                throw new BusinessException(trans('site/order/registration-fee.create_fail'));
            }

            $orderRegistrationFee->load('order');

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return $orderRegistrationFee;
    }

    /**
     * Remove.
     *
     * @param string $id
     *
     * @throws \Exception
     *
     * @return bool
     */
    public function remove(string $id): bool
    {
        $id   = SiteOrderRegistrationFee::decodeUid($id);

        return $this->delete($id);
    }

    /**
     * Delete.
     *
     * @param int $id
     *
     * @throws \Exception
     *
     * @return bool
     */
    public function delete(int $id): bool
    {
        /** @var SiteOrderRegistrationFee $orderRegistrationFee */
        $orderRegistrationFee = $this->find($id);

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            $this->orderService->delete($orderRegistrationFee->order_id);

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return true;
    }
}
